package gui;

import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;

import javax.swing.JFrame;

import universe.Universe;

public class UniverseFrame extends JFrame {
	private static final long serialVersionUID = 1L;

	public static float timeInterval = 1f;
	private UniversePanel2D panel;
	private Universe universe;

	public UniverseFrame(Universe u, int maxX, int maxY) {
		setTitle("Simulador fuerza gravitatoria");
		universe = u;
		addWindowListener(new MainWindowListener());
		panel = new UniversePanel2D(u);
		panel.setOrigin(maxX / 4, maxY / 4);
		setSize(maxX, maxY);
		add(panel);
		addKeyListener(new MyKeyListener() {
			@Override
			public void keyPressed(KeyEvent e) {
				executeKey(e.getKeyCode());
			}
		});
		addMouseWheelListener(new MouseWheelListener() {
			@Override
			public void mouseWheelMoved(MouseWheelEvent e) {
				executeMouseWheelComand(e.getWheelRotation());
			}
		});
		addMouseMotionListener(new MouseMotionListener() {
			private int x = -1;
			private int y = -1;

			@Override
			public void mouseMoved(MouseEvent e) {
				x = -1;
				y = -1;
			}

			@Override
			public void mouseDragged(MouseEvent e) {
				if (x != -1 && y != -1) {
					int newX = panel.getXOrigin() + (e.getX() - x);
					int newY = panel.getYOrigin() + (e.getY() - y);
					panel.setOrigin(newX, newY);
				}
				x = e.getX();
				y = e.getY();
			}
		});
	}

	public void refresh() {
		panel.updateUI();
	}

	private void executeKey(int keyCode) {
		int numberOfTimes = 3;
		if (keyCode == KeyEvent.VK_PLUS || keyCode == KeyEvent.VK_ADD) {
			timeInterval++;
		} else if (keyCode == KeyEvent.VK_MINUS
				|| keyCode == KeyEvent.VK_SUBTRACT) {
			timeInterval--;
		} else if (keyCode == KeyEvent.VK_LEFT) {
			panel.increaseX(numberOfTimes);
		} else if (keyCode == KeyEvent.VK_RIGHT) {
			panel.decreaseX(numberOfTimes);
		} else if (keyCode == KeyEvent.VK_UP) {
			panel.increaseY(numberOfTimes);
		} else if (keyCode == KeyEvent.VK_DOWN) {
			panel.decreaseY(numberOfTimes);
		}
	}

	private void executeMouseWheelComand(int mouseRotation) {
		if (mouseRotation == -1) {
			try {
				panel.decreaseScale(2);
			} catch (IllegalArgumentException ex) {
			}
		} else if (mouseRotation == 1) {
			panel.inscreaseScale(2);
		}
	}

	public void update() {
		universe.update(timeInterval);
		refresh();
	}
}
